# Create your tests here.

import datetime

from django.test.client import Client
from django.test import TestCase

from django.http import HttpRequest

from models import *

class MyTestCase(TestCase):
    def setUp(self):
        self.client = Client()
        
    def _new_post(self):
        return Post(title="<p>Titulo</p>", content="<h1>Conteudo</h1>", date=datetime.datetime.now(), author="Teste")
    
    def _new_comment(self):
        return Comment(author="Andre", content="<h1>Conteudo</h1>")

class TestIndex(MyTestCase):
    def test_index(self):
        response = self.client.get('/codingdojo/blog/')
        self.failUnlessEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "blog/index.html")
        
    def test_index_load_posts(self):
        post = Post(title="primeiro post", author="daniel", 
                    date=datetime.datetime.now(), content="ola!")
        post.save()
        
        response = self.client.get('/codingdojo/blog/')
        self.failUnlessEqual(response.status_code, 200)
        self.assertTrue(post in response.context['posts'])
        self.assertTemplateUsed(response, "blog/index.html")
        
    
    def test_index_post_order(self):
        post1 = Post(title="primeiro post", author="daniel", 
                    date=datetime.datetime(month=8,day=21,year=2008), content="ola!")
        post1.save()
        
        post2 = Post(title="segundo post", author="daniel", 
                    date=datetime.datetime(month=8,day=22,year=2008), content="ola2!")
        post2.save()
        
        response = self.client.get('/codingdojo/blog/')
        self.failUnlessEqual(response.status_code, 200)
        self.assertTrue(post2 == response.context['posts'][0])
        self.assertTemplateUsed(response, "blog/index.html")
        
    def test_index_post_title_link(self):
        post = self._new_post()
        post.save()
        
        response = self.client.get('/codingdojo/blog/')
        self.assertTrue("<a href='/codingdojo/blog/post/" + str(post.id)+ "'><p>Titulo</p></a>" in response.content)             
    
    def test_output_html(self):
        post = Post(title="<>", date=datetime.datetime.now())
        post.save()
        response = self.client.get('/codingdojo/blog/')
        self.assertTrue('<>' in response.content)
    
    def test_post_html(self):
        post = Post(title="<p>Titulo</p>", content="<h1>Conteudo</h1>", date=datetime.datetime.now(), author="<strong>Teste</strong>")
        post.save()
        response = self.client.get('/codingdojo/blog/')
        self.assertTrue('<p>Titulo</p>' in response.content)
        self.assertTrue('<h1>Conteudo</h1>' in response.content)
        self.assertTrue('<strong>Teste</strong>' not in response.content)

class TestNew(MyTestCase): 
    def test_link_new(self):
        ""
        response = self.client.get('/codingdojo/blog/')
        self.assertTrue('<a href="/codingdojo/blog/new/">novo</a>' in response.content)
      
    def test_new_post(self):
        response = self.client.get('/codingdojo/blog/new/')
        self.failUnlessEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "blog/new.html")
    
    def test_new_post_creation(self):
        response = self.client.post('/codingdojo/blog/new/',
                                    {'title' : 'meu primeiro post',
                                     'author':'daniel',
                                     'content': 'ola galera!'})
        
        self.assertRedirects(response, '/codingdojo/blog/')
        
        self.assertTrue(len(Post.objects.all()) == 1)
        self.assertTrue('meu primeiro post' == Post.objects.all()[0].title)
        self.assertTrue('daniel' == Post.objects.all()[0].author)
        self.assertTrue('ola galera!' == Post.objects.all()[0].content)
        
class TestPost(MyTestCase):
    def test_post_url(self):
        post = self._new_post()
        post.save()

        response = self.client.get('/codingdojo/blog/post/'+str(post.id))
        self.failUnlessEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "blog/post.html")
        
    def test_post_content(self):
        post = self._new_post()
        post.save()

        response = self.client.get('/codingdojo/blog/post/'+str(post.id))        
        self.assertTrue(post.title in response.content)        
        self.assertTrue(post.author in response.content)        
        self.assertTrue(str(post.date) in response.content)        
        self.assertTrue(post.content in response.content) 

class TestRemove(MyTestCase):
    def test_remove_post_html(self):
        post = Post(title="<p>Titulo</p>", content="<h1>Conteudo</h1>", date=datetime.datetime.now(), author="<strong>Teste</strong>")
        post.save()
        response = self.client.get('/codingdojo/blog/')
        self.assertTrue('<a href="/codingdojo/blog/remove/' + str(post.id) + '">remover</a>' in response.content)
        
    def test_remove_post(self):
        post = Post(title="<p>Titulo</p>", content="<h1>Conteudo</h1>", date=datetime.datetime.now(), author="<strong>Teste</strong>")
        post.save()
        response = self.client.get('/codingdojo/blog/remove/' + str(post.id))                
        self.assertEquals(0, len(Post.objects.all()))
        
#    TODO: Quebrar o redirect em assertResponse 302 e em client.get    
    def test_message_removed_post(self):
        post = Post(title="<p>Titulo</p>", content="<h1>Conteudo</h1>", date=datetime.datetime.now(), author="<strong>Teste</strong>")
        post.save()
        response = self.client.get('/codingdojo/blog/remove/' + str(post.id))                
        self.assertTrue('Post removido com sucesso' == self.client.session['message'])
        self.assertRedirects(response, '/codingdojo/blog/')
    
        try:
            self.client.session['message']
            self.fail('nao removeu a mensagem de removido')
        except KeyError:
            pass
        
    def test_remove_inexisting_post(self):
        "when i try remove a post that does not exist should redirect to /"
        post = Post(title="<p>Titulo</p>", content="<h1>Conteudo</h1>", date=datetime.datetime.now(), author="<strong>Teste</strong>")
        post.save()
        response = self.client.get('/codingdojo/blog/remove/' + str(10))
        self.assertRedirects(response, '/codingdojo/blog/')
        self.assertEquals(1, len(Post.objects.all()))
        
class TestRSS(MyTestCase):
    def test_link_rss(self):
        ""
        response = self.client.get('/codingdojo/blog/')
        self.assertTrue('<a href="/codingdojo/blog/rss/recent/">rss</a>' in response.content)

    def test_url_rss(self):
        response = self.client.get('/codingdojo/blog/rss/recent')
        self.failUnlessEqual(response.status_code, 301)
    
    def test_content_rss(self):
        "with a post saved, i try to get the rss and the post should come within"
        post = Post(title="<p>Titulo</p>", content="<h1>Conteudo</h1>", date=datetime.datetime.now(), author="Teste")
        post.save()
        target = RecentEntries()
        self.assertTrue(len(target.items()) == 1)
    
    def test_order_rss(self):
        "with two posts saved, the rss should be in decrescent date order"
        p1 = Post(title="post 1", content="<h1>Conteudo</h1>", date=datetime.datetime(month=9,day=18,year=2008), author="Teste")
        p1.save()
        p2 = Post(title="post 2", content="<h1>Conteudo</h1>", date=datetime.datetime(month=9,day=19,year=2008), author="Teste")
        p2.save()
        target = RecentEntries()
        self.assertTrue(p2.id == target.items()[0].id)
        self.assertTrue(p1.id == target.items()[1].id)
    
    def test_maximum_rss(self):
        "the limit of posts in rss is 20"
        for i in range(1,21):
            p = Post(title="post " + str(i), content="<h1>Conteudo</h1>", date=datetime.datetime(month=9,day=i,year=2008), author="Teste")
            p.save()

        target = RecentEntries()
        self.assertEquals(20, len(target.items()))
    
    def test_content_fields_rss(self):
        "test of the fields of the post"
        p1 = Post(title="post 1", content="conteudo 1", date=datetime.datetime(month=9,day=18,year=2008), author="autor 1")
        p1.save()
        
class TestComment(MyTestCase):
    def test_comment_instance(self):
        post = self._new_post()
        post.save()
        self.assertTrue(post.comment_set.count() == 0)
        c = Comment(post=post, author="daniel", content="my comment", date=datetime.datetime.now())
        c.save()
        self.assertTrue(post.comment_set.count() == 1)
        
    def test_new_comment_creation(self):
        c = self._new_comment()
        p = self._new_post()
        p.save()
        c.post = p    
        response = self.client.post('/codingdojo/blog/post/' + str(p.id) +'/comment/new/', 
                                    {'author': c.author,                                     
                                     'content': c.content}
                                    )
        self.assertTrue(Comment.objects.count() == 1)
        
    def test_verify_comments(self):
        p = self._new_post()
        p.save()
        c = self._new_comment()
        c.date = datetime.datetime.now()
        p.comment_set.add(c)
        response = self.client.get('/codingdojo/blog/post/' + str(p.id))
        self.assertTrue(c == response.context['comments'][0])
        